//
//  GFSearchFoodViewController.m
//  GoodFood
//
//  Created by dllo on 15/11/5.
//  Copyright © 2015年 荣伟峰. All rights reserved.
//

#import "GFSearchFoodViewController.h"

@interface GFSearchFoodViewController ()<UISearchControllerDelegate, UISearchBarDelegate, UISearchResultsUpdating, UITableViewDataSource, UITableViewDelegate, DetialsViewControllerDelegate>
@property (nonatomic, strong) UIView *barView;
@property (nonatomic, strong) UISearchController *searchController;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UIView *searchView;
@property (nonatomic, strong) UIView *backView;
@property (nonatomic, strong) UILabel *hotLabel;
@property (nonatomic, strong) NSMutableArray *searchArr;

/* 刷新使用的页数 */
@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, assign) NSInteger num;/* 判断tableView隐藏 */
@end

@implementation GFSearchFoodViewController

- (void)viewWillAppear:(BOOL)animated {
    
    self.navigationController.navigationBarHidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    UIView *view = (UIView *)[self.navigationController.view viewWithTag:10001];
    view.hidden = YES;
    [self.view addSubview:self.barView];
    [self.barView addSubview:self.backButton];
    [self.barView addSubview:self.searchView];
    [self.searchView addSubview:self.searchController.searchBar];
    
    
    
    
}


#pragma mark - 设置barView
- (void)creatSearchBarView {
    
    UIView *view = (UIView *)[self.navigationController.view viewWithTag:10001];
    
    self.barView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenWidth / 375.0 * 64)];
    self.barView.backgroundColor = [UIColor colorWithRed:190/255.0 green:231/255.0 blue:233/255.0 alpha:0.8];
    [view addSubview:self.barView];
    
    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    self.backButton.frame = CGRectMake(0, ScreenWidth / 375 * 22, ScreenWidth / 375 * 40, ScreenWidth / 375 * 40);
    //    button.backgroundColor = [UIColor greenColor];
    
    [self.backButton addTarget:self action:@selector(backToLastVC:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.backButton setImage:[UIImage imageNamed:@"houtui1"] forState:UIControlStateNormal];
    
    [self.barView addSubview:self.backButton];
    self.view.backgroundColor = [UIColor whiteColor];
}

/* 返回上一个VC */
- (void)backToLastVC:(UIButton *)button {
    
    self.searchController.active = NO;
    [self.barView removeFromSuperview];
    
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - 设置一个搜索控制器
- (void)creatSearchController {
    
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    
    /* 签订三个协议 */
    self.searchController.delegate = self;
    self.searchController.searchResultsUpdater = self;
    self.searchController.searchBar.delegate = self;
    
    
    
    self.searchView = [[UIView alloc] initWithFrame:CGRectMake(ScreenWidth / 375 * 50, ScreenWidth / 375 * 20, ScreenWidth / 375 * 275, ScreenWidth / 375 * 40)];
    //    searchView.backgroundColor = [UIColor whiteColor];
    
    
    /* 关闭才能滑动 */
    self.searchController.dimsBackgroundDuringPresentation = NO;
    self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, ScreenWidth / 375 * 40.0);
    
    
    
    [self.barView addSubview:self.searchView];
    [self.searchView addSubview:self.searchController.searchBar];
    
    [self.searchController.searchBar sizeToFit];

}

#pragma mark - 处理数据
- (void)handleData {
    NSString *searchString = self.searchController.searchBar.text;
    
    NSString *firstStr = @"http://food.boohee.com/fb/v1/foods/search?q=";
    NSString *lastStr = @"&page=1";
    
    NSString *urlStr = [[firstStr stringByAppendingString:searchString] stringByAppendingString:lastStr];
    

    
  
    
    
    
    [self.searchArr removeAllObjects];
    
    [AFNetHandle GETWithURL:urlStr body:nil httpHead:nil responseStyle:JSON success:^(id result) {
        
        
        NSArray *arr = [NSArray arrayWithArray:[result objectForKey:@"foods"]];
        
        for (NSDictionary *dic in arr) {
            
            GFDetialsModel *deModel = [GFDetialsModel detailsModelWithDintionary:dic];
            
            //            NSLog(@"-------------%@", deModel.name);
            
            
            [self.searchArr addObject:deModel];
        }
        if (arr.count != 0) {
            if (self.searchArr.count < 20) {
                self.tableView.footer.hidden = YES;
            } else {
                self.tableView.footer.hidden = NO;
            }
        } else {
            self.tableView.footer.hidden = YES;
        }
        [self.tableView reloadData];
       
        
    } fail:^(NSError *error) {
        
    }];
}

#pragma mark - searchController代理方法
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
    if (self.num == 1) {
        
        self.tableView.hidden = YES;
        self.backView.hidden = NO;
        self.num = 0;
        
    } else {
        
        self.tableView.hidden = NO;
        self.backView.hidden = YES;
        
    }
    [self handleData];
    if (self.searchArr.count > 0) {
        
        return;
    }
    
    
    
    self.pageNum = 2;
    
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
    //    NSLog(@"--------------------------------------------------001");
    
    NSString *searchString = self.searchController.searchBar.text;
    
    NSString *firstStr = @"http://food.boohee.com/fb/v1/foods/search?q=";
    NSString *lastStr = @"&page=1";
    
    NSString *urlStr = [[firstStr stringByAppendingString:searchString] stringByAppendingString:lastStr];

    
    [self.searchArr removeAllObjects];
    
    [AFNetHandle GETWithURL:urlStr body:nil httpHead:nil responseStyle:JSON success:^(id result) {
        
        
        NSArray *arr = [NSArray arrayWithArray:[result objectForKey:@"foods"]];
        
        for (NSDictionary *dic in arr) {
            
            GFDetialsModel *deModel = [GFDetialsModel detailsModelWithDintionary:dic];
            
            [self.searchArr addObject:deModel];
        }
        
        //        NSLog(@"=========%ld", self.searchArr.count);
        if (arr.count != 0) {
            if (self.searchArr.count < 20) {
                self.tableView.footer.hidden = YES;
            } else {
                self.tableView.footer.hidden = NO;
            }
        } else {
            self.tableView.footer.hidden = YES;
        }
        [self.tableView reloadData];
        
    } fail:^(NSError *error) {
        
    }];
    
    
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    
    self.tableView.hidden = YES;
    
    self.num = 0;
    self.num++;
    
    [self.searchArr removeAllObjects];
    
}


#pragma mark - 创建tableView
- (void)creatTableView {
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, ScreenWidth / 375 * 64, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.rowHeight = ScreenWidth / 375 * 50;
    
    /* 重用池 */
    [self.tableView registerClass:[GFSearchFoodCell class] forCellReuseIdentifier:@"reuse"];
    

    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(pushUp:)];
    self.tableView.footer.hidden = YES;
    [self.view addSubview:self.tableView];
    
}




/* 上拉加载 */
- (void)pushUp:(MJRefreshFooter *)footer {
    
    //    self.searchController.active = NO;
    
    NSString *searchString = self.searchController.searchBar.text;
    
    NSString *firstStr = @"http://food.boohee.com/fb/v1/foods/search?q=";
    NSString *lastStr = [NSString stringWithFormat:@"&page=%ld", self.pageNum];
    
    NSString *urlStr = [[firstStr stringByAppendingString:searchString] stringByAppendingString:lastStr];
    

    
    //    NSLog(@"%@", urlStr);
    
    [AFNetHandle GETWithURL:urlStr body:nil httpHead:nil responseStyle:JSON success:^(id result) {
        
        NSArray *arr = [result objectForKey:@"foods"];
        
        for (NSDictionary *dic in arr) {
            
            GFDetialsModel *deModel = [GFDetialsModel detailsModelWithDintionary:dic];
            
            [self.searchArr addObject:deModel];
            
        }
        
        [self.tableView reloadData];
        
        
        [self.tableView.footer endRefreshing];
        if (arr.count != 0) {
            if (self.searchArr.count < 20) {
                self.tableView.footer.hidden = YES;
            } else {
                self.tableView.footer.hidden = NO;
            }
        } else {
            self.tableView.footer.hidden = YES;
        }
        
    } fail:^(NSError *error) {
        
    }];
    
    self.pageNum++;
    
}


#pragma mark - tableView DataSource代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    //    NSLog(@"%ld", self.searchArr.count);
    
    return self.searchArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    GFSearchFoodCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    
    GFDetialsModel *deModel = [self.searchArr objectAtIndex:indexPath.row];
    
    cell.highLightWord = self.searchController.searchBar.text;
    
    cell.deModel = deModel;
    
    
    
    return cell;
}

#pragma mark - 点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    GFDetialsViewController *detailsVC = [[GFDetialsViewController alloc] init];
    
    GFDetialsModel *deModel = [self.searchArr objectAtIndex:indexPath.row];
    
    detailsVC.searchArr = self.searchArr;
    detailsVC.searchStr = self.searchController.searchBar.text;
    
    self.searchController.active = NO;
    [self.barView removeFromSuperview];
    
    [self.navigationController pushViewController:detailsVC animated:YES];
    
    detailsVC.food_code = deModel.code;
    
    detailsVC.pageNum = self.pageNum;
    
    detailsVC.delegate = self;
 
    
}

#pragma mark - detail协议方法
- (void)giveSearchValue:(NSString *)value withSearchArr:(NSMutableArray *)arr withPage:(NSInteger)pageNum {
    

    self.searchController.active = YES;
    
    self.searchController.searchBar.text = value;
    self.searchArr = arr;
    self.pageNum = pageNum;
    
    //    NSLog(@"-------------%ld-------%ld", self.searchArr.count, self.pageNum);
}


/* 消除searchBar后面的背景颜色 */
- (void)removeButtonLayout:(UIView *)current {
    if ([current isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
        [current removeFromSuperview];
    } else if ([current isKindOfClass:NSClassFromString(@"UISearchBarTextField")]) {
        current.backgroundColor = [UIColor colorWithRed:0.000 green:0.129 blue:0.264 alpha:1.000];
        UITextField *textField = (UITextField *)current;
        textField.textColor = [UIColor groupTableViewBackgroundColor];
    }
    
    for (UIView *view in current.subviews) {
        [self removeButtonLayout:view];
    }
}

#pragma mark - 创建热门搜索界面
- (void)creatHotButton {
    
    [AFNetHandle GETWithURL:@"http://food.boohee.com/fb/v1/keywords" body:nil httpHead:nil responseStyle:JSON success:^(id result) {
        
        self.backView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenWidth / 375.0 * 64, ScreenWidth, ScreenHeight - ScreenWidth / 375.0 * 64)];
        self.backView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:self.backView];
        
        self.hotLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth / 375.0 * 30, ScreenWidth / 375.0 * 40, ScreenWidth / 375.0 * 100, ScreenWidth / 375.0 * 30)];
        self.hotLabel.text = @"热门搜索";
        [self.backView addSubview:self.hotLabel];

        
        NSArray *arr = [result objectForKey:@"keywords"];
        
        //        NSLog(@"%@", [arr objectAtIndex:0]);
        
        int k = 0;
        for (int i = 0; i < 2; i++) {
            
            for (int j = 0; j < 5; j++) {
                
                UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
                button.frame = CGRectMake(ScreenWidth / 375.0 * 20 + ScreenWidth / 375.0 * 69 * j, ScreenWidth / 375.0 * 80 + ScreenWidth / 375.0 * 40 * i, ScreenWidth / 375.0 * 59, ScreenWidth / 375.0 * 30);
                [button setTitle:[arr objectAtIndex:k] forState:UIControlStateNormal];
                [button setTintColor:[UIColor lightGrayColor]];
                button.layer.cornerRadius = 10;
                button.layer.masksToBounds = YES;
                button.layer.borderWidth = 1;
                button.tag = k + 1;
                button.layer.borderColor = [[UIColor colorWithRed:0.592 green:0.995 blue:0.767 alpha:1.000]CGColor];
                [button addTarget:self action:@selector(buttonHot:) forControlEvents:UIControlEventTouchUpInside];
                [self.backView addSubview:button];
                k++;
            }
            
        }

        
        [self.waitView removeFromSuperview];
        
    } fail:^(NSError *error) {
        [self.waitView removeFromSuperview];
    }];
    
}

- (void)buttonHot:(UIButton *)button {
    
    self.searchController.active = YES;
    
    self.searchController.searchBar.text = button.titleLabel.text;
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    

    
    [self creatHotButton];
    [self creatTableView];
    [self creatSearchBarView];
    [self creatSearchController];
    [self.view bringSubviewToFront:self.waitView];
    
    
    self.tableView.hidden = YES;
    
    [self removeButtonLayout:self.barView];
    
    self.searchArr = [NSMutableArray array];
    
  
    
       // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
